//
//  JYPullDownRefreshController.swift
//  01.weibo
//
//  Created by 谢玉锋 on 16/7/19.
//  Copyright © 2016年 itheima.cn. All rights reserved.
//

import UIKit
/// 刷新控件的高度
private let JYPullDownRefreshControlHeight: CGFloat = 60
//下拉刷新几种状态
enum JYPullDownRefreshControllerStatus: Int {

    case Normal  // 箭头朝下, 下拉刷新
    case PullToRefresh // 箭头朝上, 释放刷新
    case Refreshing // 正在刷新
}
class JYPullDownRefreshController: UIView {
 
    //1.定义一个闭包作为属性
    var pullDownRefreshHandler: (()->())?
    
    //定义一个属性引用父控件 (下面调用方法时,可以获得,另外要监听谁的属性,就用谁来调用)
    var superScrollView: UIScrollView?
    
    //设置属性记录当前状态(默认当前为normal)  状态的切换是根据tableView.ContentOffest.y值来计算
    //当前状态(默认正常)
    var curenntStatus = JYPullDownRefreshControllerStatus.Normal {
        didSet {
            switch curenntStatus{
            case .Normal:
                JYPrint("Normal")
                fhlView.hidden = true
                arrowView.hidden = false
                messageLabel.text = "下拉刷新"
                UIView.animateWithDuration(DefaultAnimationTime, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformIdentity
                })
                
            case .PullToRefresh:
                JYPrint("PullToRefresh")
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(DefaultAnimationTime, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                JYPrint("Refreshing")
                // 风火轮转, 文字 "正在刷新...", 不要滚动到导航栏下面
                arrowView.hidden = true
                fhlView.hidden = false
                messageLabel.text = "正在刷新..."
                //创建动画
                let animation = CABasicAnimation(keyPath: "transform.rotation")
                //配置参数
                animation.toValue = M_PI*2
                animation.repeatCount = MAXFLOAT
                animation.duration = 0.5//重复一次的时间
                animation.removedOnCompletion = false
                //添加动画
                // 给动画加forKey: 如果下次再添加一个和之前已经存在的动画,先停止之前的动画,在使用这次的动画, 防止动画重复添加
                fhlView.layer.addAnimation(animation, forKey: "animation")
                
                UIView.animateWithDuration(DefaultAnimationTime, animations: { () -> Void in
                    self.superScrollView?.contentInset.top += JYPullDownRefreshControlHeight
                })
                //2.告诉别人开始刷新状态
                pullDownRefreshHandler?()
            }
        }
    }
    //开始刷新
    func startRefreshing() {
    curenntStatus = JYPullDownRefreshControllerStatus.Refreshing
    }
    //下来刷新后,本空间回到Normal状态
    func endRefreshing() {
        // Refreshing切换到Normal
        curenntStatus = .Normal
        // 只有是从Refreshing切换Normal才需要去 contentInset.top - HMPullDownRefreshControlHeight
        // 让tableView往上走HMPullDownRefreshControlHeight, 刷新控件就看不到了
    UIView.animateWithDuration(DefaultAnimationTime) { () -> Void in
        self.superScrollView?.contentInset.top -= JYPullDownRefreshControlHeight
        }
    
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        //自己设置frame
        let newFrame = CGRectMake(0, -JYPullDownRefreshControlHeight, UIScreen.mainScreen().bounds.width, JYPullDownRefreshControlHeight)
        super.init(frame: newFrame)
        prepareUI()
        
    }
    private func prepareUI() {
        
//    backgroundColor = UIColor.orangeColor()
        //添加子控件
        addSubview(arrowView)
        addSubview(fhlView)
        addSubview(messageLabel)
        fhlView.hidden = true
        //添加约束
        fhlView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        arrowView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(fhlView)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(fhlView.snp_trailing).offset(10)
            make.centerY.equalTo(arrowView)//
        }
    }
    
    // 当控件被添加到父空件后会调用这个方法, 在这个时候可以拿到父控件 (子父控件关系)
    override func willMoveToSuperview(newSuperview: UIView?) {
        if let scrollView = newSuperview as? UIScrollView {
        superScrollView = scrollView
            // 使用KVO来监听scrollView的滚动
            // 要监听谁的属性,就用谁来调用 : superScrollView 调用
            // observer: 谁来处理监听事件 : self
            // forKeyPath: 想监听的属性 : "contentOffset"
            // options: 监听选项, 新值,老得值: 给 [] 表示不关心
            // context: 上下文 绘图用的比较多
        superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
            
        }
    }
    
    /*
    Normal: contentOffset.y > -124  -100
    PullToRefresh: contentOffset.y < -124   -130
    
    -124 = -(superScrollView?.contentInset + HMPullDownRefreshControlHeight)
    解析: superScrollView!.contentInset.top 相当于tableviewcell 相对上面的约束高度,就这么简单
    */
    
 // 实现KVO的监听方法, 方法是固定的
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        JYPrint("tableView滚动了 \(superScrollView?.contentOffset.y)")
        
        if superScrollView!.dragging {
        //在拽时, 且 当前状态是 PullToRefresh时
            if curenntStatus == .PullToRefresh && superScrollView?.contentOffset.y > -(JYPullDownRefreshControlHeight + superScrollView!.contentInset.top) {
            JYPrint("切换到正常状态")
                //再次记录当前状态
                curenntStatus = .Normal
            }else if curenntStatus == .Normal && superScrollView?.contentOffset.y < -(JYPullDownRefreshControlHeight + superScrollView!.contentInset.top) {
            JYPrint("切换到下拉刷新状态")
                //再次记录当前状态
                curenntStatus = .PullToRefresh
            }
            
        }else if curenntStatus == .PullToRefresh{
            //不在拖拽状态下
            JYPrint("切换正在刷新状态")
            //再次记录当前状态
            curenntStatus = .Refreshing
        }
        
    }
// 注意用KVO要移除监听 , OC中类消失会调用 dealloc方法 ,swift中调用下面方法
    deinit {
    removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //懒加载控件
    //箭头
    private lazy var arrowView: UIImageView = UIImageView(imgName: "tableview_pull_refresh")
    //风火轮
    private lazy var fhlView: UIImageView = UIImageView(imgName: "tableview_loading")
    //状态label
    private lazy var messageLabel: UILabel = {
    let label = UILabel(fontSize: 14, textColor: UIColor.orangeColor())
    label.text = "下拉刷新"
    return label
    }()
    
}








